package com.jzqf.android.alive.alive

//import io.dcloud.uts.console
import android.app.Activity
import android.app.AlarmManager
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.ServiceInfo
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.IBinder
import android.os.PowerManager
import android.os.SystemClock
import android.provider.Settings
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import com.jzqf.android.alive.R

interface PermissionCallback {
    fun onPermissionGranted()
    fun onPermissionDenied()
}

object PermissionManager {
    const val REQUEST_IGNORE_BATTERY_CODE = 1002
    const val REQUEST_OVERLAY_CODE = 1003
    const val REQUEST_ALARM_PERMISSION = 1004

    fun requestBatteryOptimizationPermission(context: Context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
            if (!powerManager.isIgnoringBatteryOptimizations(context.packageName)) {
                val intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
                intent.data = Uri.parse("package:${context.packageName}")
                try {
                    if (context is Activity) {
                        context.startActivityForResult(intent, REQUEST_IGNORE_BATTERY_CODE)
                    } else {
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        context.startActivity(intent)
                    }
                } catch (e: Exception) {
                    Log.d("PermissionManager", "请求忽略电池优化失败", e)
                }
            }
        }
    }

    fun requestOverlayPermission(context: Context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(context)) {
            val intent = Intent(
                Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                Uri.parse("package:${context.packageName}")
            )
            try {
                if (context is Activity) {
                    context.startActivityForResult(intent, REQUEST_OVERLAY_CODE)
                } else {
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    context.startActivity(intent)
                }
            } catch (e: Exception) {
                Log.d("PermissionManager", "请求悬浮窗权限失败", e)
            }
        }
    }

    fun requestExactAlarmPermission(context: Context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
            if (!alarmManager.canScheduleExactAlarms()) {
                val intent = Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM)
                intent.data = Uri.parse("package:${context.packageName}")
                if (context is Activity) {
                    context.startActivityForResult(intent, REQUEST_ALARM_PERMISSION)
                } else {
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    context.startActivity(intent)
                }
            }
        }
    }

    fun showAutoStartGuide(context: Context) {
        val manufacturer = Build.MANUFACTURER.lowercase()

        val message = when {
            manufacturer.contains("huawei") || manufacturer.contains("honor") -> "华为/荣耀：请进入手机管家 > 启动管理 > 允许应用自启动"

            manufacturer.contains("vivo") -> "VIVO：请进入i管家 > 软件管理 > 自启动管理 > 允许应用自启动"

            manufacturer.contains("oppo") || manufacturer.contains("realme") || manufacturer.contains(
                "oneplus"
            ) -> "OPPO/Realme/一加：请进入手机管家 > 权限隐私 > 自启动管理 > 允许应用自启动"

            manufacturer.contains("xiaomi") || manufacturer.contains("redmi") -> "小米/Redmi：请进入安全中心 > 应用管理 > 权限 > 自启动管理 > 允许应用自启动"

            else -> null
        }

        // message?.let {
        // 	Toast.makeText(context, it, Toast.LENGTH_LONG).show()
        // }
    }
}


object KeepAliveManager {
    private const val TAG = "KeepAlive"
    internal const val CHANNEL_ID = "keep_alive_channel"
    internal const val NOTIFICATION_ID = 10001
    private const val ALARM_INTERVAL = 5 * 60 * 1000L // 5分钟

    private var wakeLock: PowerManager.WakeLock? = null
    private var isRunning = false
    private var customTask: (() -> Unit)? = null
    private var onServiceStopped: (() -> Unit)? = null // 新增回调接口

    fun start(
        context: Context,
        task: () -> Unit,
    ) {
        if (isRunning) return
        isRunning = true
        customTask = task

        startForegroundService(context)
        requestNecessaryPermissions(context)
        registerScreenReceiver(context)
        scheduleAlarm(context)

        Log.d(TAG, "保活服务已启动")
    }

    fun stop(
        context: Context,
        onServiceStopped: (() -> Unit)? = null,
    ) {
        if (!isRunning) return
        isRunning = false

        this.onServiceStopped = onServiceStopped // 保存回调接口

        cancelAlarm(context)
        unregisterScreenReceiver(context)
        releaseWakeLock()
        context.stopService(Intent(context, KeepAliveService::class.java))

        // 执行回调接口
        this.onServiceStopped?.invoke()

        Log.d(TAG, "保活服务已停止")
    }

    fun runCustomTask() {
        customTask?.invoke()
    }

    internal fun startForegroundService(context: Context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(Intent(context, KeepAliveService::class.java))
        } else {
            context.startService(Intent(context, KeepAliveService::class.java))
        }
    }

    internal fun createNotification(context: Context): Notification {
        createNotificationChannel(context)
        return NotificationCompat.Builder(context, CHANNEL_ID)
            .setContentTitle(context.getString(R.string.app_name)).setContentText("APP is 保活中")
            .setSmallIcon(R.mipmap.ic_launcher).setPriority(NotificationCompat.PRIORITY_LOW)
            .setColor(Color.BLUE).setOngoing(true).build()
    }

    private fun createNotificationChannel(context: Context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                "保活服务",
                NotificationManager.IMPORTANCE_LOW,
            ).apply {
                description = "确保应用在后台持续运行"
                enableLights(false)
                enableVibration(false)
                setShowBadge(false)
            }

            val manager = context.getSystemService(NotificationManager::class.java)
            manager.createNotificationChannel(channel)
        }
    }

    private fun requestNecessaryPermissions(context: Context) {
        PermissionManager.requestBatteryOptimizationPermission(context)
        PermissionManager.requestOverlayPermission(context)
        PermissionManager.requestExactAlarmPermission(context)
        PermissionManager.showAutoStartGuide(context)
    }

    internal fun scheduleAlarm(context: Context) {
        val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        val intent = Intent(context, AlarmReceiver::class.java)
        val pendingIntent = PendingIntent.getBroadcast(
            context,
            0,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
        )

        val triggerTime = SystemClock.elapsedRealtime() + ALARM_INTERVAL

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarmManager.setExactAndAllowWhileIdle(
                AlarmManager.ELAPSED_REALTIME_WAKEUP,
                triggerTime,
                pendingIntent,
            )
        } else {
            alarmManager.setExact(
                AlarmManager.ELAPSED_REALTIME_WAKEUP,
                triggerTime,
                pendingIntent,
            )
        }

        Log.d(TAG, "定时唤醒已设置，间隔: ${ALARM_INTERVAL / 1000}秒")
    }

    private fun cancelAlarm(context: Context) {
        val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        val intent = Intent(context, AlarmReceiver::class.java)
        val pendingIntent = PendingIntent.getBroadcast(
            context,
            0,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
        )
        alarmManager.cancel(pendingIntent)
    }

    fun acquireWakeLock(context: Context) {
        if (wakeLock?.isHeld == true) return

        val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "KeepAlive::WakeLock")
        wakeLock?.acquire(10 * 60 * 1000L /*10分钟*/)
        Log.d(TAG, "WakeLock已获取")
    }

    fun releaseWakeLock() {
        wakeLock?.let {
            if (it.isHeld) {
                it.release()
                Log.d(TAG, "WakeLock已释放")
            }
        }
        wakeLock = null
    }

    const val ACTION_FINISH_ONE_PIXEL = "uts.sdk.modules.tKeepaliveApi.FINISH_ONE_PIXEL"

    object ScreenReceiver : BroadcastReceiver() {
        override fun onReceive(
            context: Context,
            intent: Intent,
        ) {
            when (intent.action) {
                Intent.ACTION_SCREEN_OFF -> {
                    Log.d(TAG, "屏幕关闭")
                }

                Intent.ACTION_SCREEN_ON -> {
                    Log.d(TAG, "屏幕开启")
                    KeepAliveManager.runCustomTask()
                }

                KeepAliveManager.ACTION_FINISH_ONE_PIXEL -> {
                    Log.d(TAG, "关闭1像素Activity")
                }
            }
        }
    }

    private var screenReceiver: BroadcastReceiver? = null

    private fun registerScreenReceiver(context: Context) {
        screenReceiver = ScreenReceiver
        val filter = IntentFilter().apply {
            addAction(Intent.ACTION_SCREEN_OFF)
            addAction(Intent.ACTION_SCREEN_ON)
            addAction(ACTION_FINISH_ONE_PIXEL)
            // 添加更多保护措施
            priority = IntentFilter.SYSTEM_HIGH_PRIORITY
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
            context.registerReceiver(screenReceiver, filter, null, null, Context.RECEIVER_NOT_EXPORTED)
        } else {
            ContextCompat.registerReceiver(
                context,
                screenReceiver,
                filter,
                null,
                null,
                ContextCompat.RECEIVER_EXPORTED
            )
        }
    }

    private fun unregisterScreenReceiver(context: Context) {
        screenReceiver?.let {
            try {
                context.unregisterReceiver(it)
            } catch (e: IllegalArgumentException) {
                Log.d(TAG, "注销屏幕接收器失败", e)
            }
        }
    }
}

class KeepAliveService : Service() {
    override fun onCreate() {
        super.onCreate()
        Log.d("KeepAliveService", "服务已创建")
        KeepAliveManager.acquireWakeLock(this)
    }

    override fun onStartCommand(
        intent: Intent?,
        flags: Int,
        startId: Int,
    ): Int {
        Log.d("KeepAliveService", "服务已启动")
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
            startForeground(
                KeepAliveManager.NOTIFICATION_ID,
                KeepAliveManager.createNotification(this),
                ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC
            )
        } else {
            startForeground(
                KeepAliveManager.NOTIFICATION_ID, KeepAliveManager.createNotification(this)
            )
        }
        KeepAliveManager.runCustomTask()
        return START_STICKY
    }

    override fun onBind(intent: Intent?): IBinder? = null

    override fun onDestroy() {
        super.onDestroy()
        Log.d("KeepAliveService", "服务已销毁")
        KeepAliveManager.releaseWakeLock()
    }
}


class AlarmReceiver : BroadcastReceiver() {
    override fun onReceive(
        context: Context,
        intent: Intent,
    ) {
        Log.d("AlarmReceiver", "定时唤醒触发")
        KeepAliveManager.runCustomTask()
        KeepAliveManager.scheduleAlarm(context)
    }
}

class BootReceiver : BroadcastReceiver() {
    override fun onReceive(
        context: Context,
        intent: Intent,
    ) {
        if (intent.action == Intent.ACTION_BOOT_COMPLETED || intent.action == "android.intent.action.QUICKBOOT_POWERON" || intent.action == "com.htc.intent.action.QUICKBOOT_POWERON") {
            Log.d("BootReceiver", "设备已启动，重新启动保活服务")
            KeepAliveManager.start(context) {
                Log.d("KeepAlive", "保活任务执行中...")
            }
        }
    }
}